package dyyx.demo;

import java.util.List;

import com.google.common.collect.Lists;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.LoadBalancerBuilder;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.reactive.LoadBalancerCommand;
import com.netflix.loadbalancer.reactive.ServerOperation;

import rx.Observable;

public class RibbonDemo {

	public static void main(final String[] args) {

		List<Server> serverList = Lists.newArrayList(new Server("localhost", 8080), new Server("localhost", 8081));
		ILoadBalancer loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(serverList);

		
		for (int i = 0; i < 10; i++) {
			System.out.println(loadBalancer.chooseServer(null));
			
		}
		System.out.println("*************\n");

		
		LoadBalancerCommand<String> loadBalancerCommand = LoadBalancerCommand.<String>builder().withLoadBalancer(loadBalancer).build();
		for (int i = 0; i < 10; i++) {
			try {
				String result = loadBalancerCommand.submit(new MyServerOperation()).toBlocking().first();
				System.out.println("result:" + result);
			} catch (Throwable e) {
				System.out.println("error," + e);
			}
			System.out.println("\n");

		}
	}

	private static class MyServerOperation implements ServerOperation<String> {
		private static int seq = 0;

		public Observable<String> call(Server server) {
			seq++;
			try {
				String addr = "http://" + server.getHost() + ":" + server.getPort() + "/user/hello";
				System.out.println("invoke:" + addr);

				if (seq > 0 && seq % 2 == 0) {
					throw new Exception("error," + seq);
				}
				// mock
				/*
				 * URL url = new URL(addr); HttpURLConnection conn = (HttpURLConnection)
				 * url.openConnection(); conn.setRequestMethod("GET"); conn.connect();
				 * InputStream in = conn.getInputStream(); byte[] data = new
				 * byte[in.available()]; in.read(data);
				 */
				return Observable.just(new String(addr));
			} catch (Exception e) {
				return Observable.error(e);
			}
		}
	}

}
